package com.heima.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.api.item.ItemClient;
import com.heima.common.Result;
import com.heima.constant.MQConstant;
import com.heima.dto.DeductStockDTO;
import com.heima.order.entity.Order;
import com.heima.order.mapper.OrderMapper;
import com.heima.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuan
 * @since 2023-09-06
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ItemClient itemClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 功能描述:  下单业务
     * @return : com.heima.common.Result
     */
    @GlobalTransactional
    @Override
    public Result createOrder() {
        //1.生成订单，生成订单详情
        Order order = new Order();
        order.setTotalFee(100l);
        order.setPaymentType(true);
        order.setUserId(2l);
        order.setStatus((short)1);
        orderMapper.insert(order);
        //2.扣减库存
        List<DeductStockDTO> dtos = new ArrayList<>();
        dtos.add(new DeductStockDTO(317578l,10));
        rabbitTemplate.convertAndSend(MQConstant.CREATE_ORDER_EXCHANGE,MQConstant.DEDUCT_STOCK_RK, JSON.toJSONString(dtos));
        return new Result(200,"下单成功",true);
    }
}
